//@ts-nocheck

import { defineComponent, reactive, ref, computed, PropType } from 'vue'
import moment, { Moment, MomentInput } from 'moment'
import useMemo from '../_util/hooks/useMemo'
import { formatDate, toMoment } from './utils'

import Trigger from '../trigger'
import Icon from '../icon'
import DatePicker from './index'
import Calendar from '../calendar'
import RangeCalendar from '../calendar/RangeCalendar'

import { PickerProps } from './props'

export default defineComponent({
  name: 'x-range-picker',
  props: {
    ...PickerProps,
    prefixCls: { default: 'x-range-picker' },
    value: Array as PropType<MomentInput[]>,
    placeholder: { default: ['开始日期', '结束日期'] }
  },
  emits: ['update:value', 'change'],
  setup(props, { emit }) {
    const state = reactive({
      opend: false,
      focued: false
    })
    const inputRef1 = ref<HTMLInputElement>()

    const placeholderRef = computed(() => {
      const { placeholder } = props
      return Array.isArray(placeholder) ? placeholder : [placeholder, placeholder]
    })
    const valueRef = useMemo<Moment[]>(() => (toMoment(props.value, props.valueFormat) || []) as Moment[])

    function onChange(date: Moment[]) {
      valueRef.value = date?.map(e => e.clone())
      const val = props.valueFormat ? formatDate(date, props.valueFormat) : date?.map(e => e.clone())
      emit('update:value', val)
      emit('change', val)
    }

    function onSelect(date: Moment[]) {
      state.opend = false
      onChange(date)
    }
    function onClear(e: Event) {
      e.stopPropagation()
      onSelect([])
    }
    function onClick(e: Event) {
      if (props.disabled) return
      requestAnimationFrame(() => inputRef1.value.focus())
    }

    function onPopupVisibleChange(visble: boolean) {
      state.opend = visble
    }

    function onFocus() {
      state.focued = true
    }
    function onBlur() {
      state.focued = false
    }

    let calendarNode: JSX.Element
    function getCalendarNode() {
      if (!state.opend) return calendarNode
      const calendarProps = {
        value: valueRef.value,
        disabledDate: props.disabledDate,
        onSelect
        // onChange
      }
      calendarNode = <RangeCalendar {...calendarProps}></RangeCalendar>
      return calendarNode
    }

    return () => {
      const { prefixCls, format, disabled, clearable } = props
      const placeholder = placeholderRef.value
      const val = valueRef.value

      const cls = {
        [prefixCls]: true,
        [`${prefixCls}-focus`]: state.focued,
        [`${prefixCls}-disabled`]: disabled
      }

      const triggerProps = {
        prefixCls: `${prefixCls}-popup`,
        popup: getCalendarNode(),
        popupVisible: state.opend,
        action: disabled ? '' : 'click',
        popupAlign: {
          points: ['tl', 'bl']
        },
        onPopupVisibleChange
      }

      const inputProps = {
        class: `${prefixCls}_input`,
        disabled,
        onFocus,
        onBlur
      }

      const clearIcon = !disabled && clearable && val.length ? <Icon class={`${prefixCls}_clear`} type='cross' onClick={onClear} onMousedown={onClick}></Icon> : undefined
      const calendarIcon = clearIcon ? undefined : <Icon class={`${prefixCls}_icon`} type='calendar' onMousedown={onClick}></Icon>

      return (
        <Trigger {...triggerProps}>
          <div class={cls}>
            <input {...inputProps} placeholder={placeholder[0]} value={formatDate(val[0], format)} ref={inputRef1} />
            <span class={`${prefixCls}_separator`}> ~ </span>
            <input {...inputProps} placeholder={placeholder[1]} value={formatDate(val[1], format)} />
            {calendarIcon}
            {clearIcon}
          </div>
        </Trigger>
      )
    }
  }
})
